/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.excel.converters;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.star.framework.excel.convert.CellValueConverter;
import cn.star.framework.excel.convert.ColumnAutoMount;
import cn.star.framework.excel.convert.ValueWrapper;
import cn.star.framework.excel.converters.StringJdk8DateConverter.DateTimeDescribe;
import cn.star.framework.excel.core.Column;
import cn.star.framework.excel.core.RowWrapper;
import java.sql.Timestamp;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串转日期<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Deprecated
public class StringDateConverter implements CellValueConverter<Date, String>, ColumnAutoMount {
  public static final StringDateConverter INSTANCE = new StringDateConverter();

  /**
   * 正则表达式<br>
   *
   * <pre>
   *   ^(\\d{4}):               匹配年份
   *   [-|\\/|\\.]:             年月日之间的分隔符可以是这些
   *   (0?[1-9]|1[0-2]):        匹配月份
   *   (0?[1-9]|[12]\\d|3[01]): 匹配日期
   *   [\\s]:                   空格或任意一个字符
   *   ([01]?\\d|2[0-3]):       匹配时00 ~ 23时
   *   ([0-5]?\\d):             匹配分00 ~ 59分
   *   ([0-5]?\\d):             匹配秒00 ~ 59秒
   * </pre>
   */
  public static final String[] SUPPORT_REGEX_STR =
      new String[] {
        "^(\\d{4})[-|\\/|\\.](0?[1-9]|1[0-2])[-|\\/|\\.](0?[1-9]|[12]\\d|3[01])$",
        "^(\\d{4})[-|\\/|\\.](0?[1-9]|1[0-2])[-|\\/|\\.](0?[1-9]|[12]\\d|3[01])[\\s]+([01]?\\d|2[0-3])[:|\\/|\\.]([0-5]?\\d)$",
        "^(\\d{4})[-|\\/|\\.](0?[1-9]|1[0-2])[-|\\/|\\.](0?[1-9]|[12]\\d|3[01])[\\s]+([01]?\\d|2[0-3])[:|\\/|\\.]([0-5]?\\d)[:|\\/|\\.]([0-5]?\\d)$",
        "^(\\d{4})年(0?[1-9]|1[0-2])月(0?[1-9]|[12]\\d|3[01])[日|号]$",
        "^(\\d{4})年(0?[1-9]|1[0-2])月(0?[1-9]|[12]\\d|3[01])[日|号][\\s]+([01]?\\d|2[0-3])[时|点]([0-5]?\\d)分$",
        "^(\\d{4})年(0?[1-9]|1[0-2])月(0?[1-9]|[12]\\d|3[01])[日|号][\\s]+([01]?\\d|2[0-3])[时|点]([0-5]?\\d)分([0-5]?\\d)秒$",
      };

  @Override
  public Date convert(Column column, String v, RowWrapper rowWrapper) {
    if (StrUtil.isBlank(v)) {
      return null;
    }
    try {
      // 可能是日期字符串
      String dateTimeStr = StringDateConverter.compile(v).getValue();
      ValueWrapper<Date> wrapper = this.date(dateTimeStr, DateStringConverter.DEFAULT_DATE_FORMAT);
      if (wrapper.isSuccess()) {
        return wrapper.getValue();
      } else {
        wrapper = this.date(dateTimeStr, DatePattern.NORM_DATETIME_MINUTE_PATTERN);
      }
      if (wrapper.isSuccess()) {
        return wrapper.getValue();
      } else {
        wrapper = this.date(dateTimeStr, DatePattern.NORM_DATE_PATTERN);
      }
      if (wrapper.isSuccess()) {
        return wrapper.getValue();
      } else {
        wrapper = this.date(dateTimeStr, DatePattern.NORM_DATETIME_MS_PATTERN);
      }
      if (wrapper.isSuccess()) {
        return wrapper.getValue();
      } else {
        throw new RuntimeException(wrapper.getEx());
      }
    } catch (Exception e) {
      // 可能是时间戳
      ValueWrapper<Date> wrapper = this.timestamp(v);
      if (wrapper.isSuccess()) {
        return wrapper.getValue();
      } else {
        throw e;
      }
    }
  }

  @Override
  public String convert(Column column, ValueWrapper<Date> wrapper) {
    Date date = wrapper.getValue();
    // 默认转换为 yyyy-MM-dd HH:mm:ss
    return DateUtil.formatDateTime(date);
  }

  @Override
  public Class<?>[] getSupportTypes() {
    return new Class[] {Date.class, Timestamp.class};
  }

  private ValueWrapper<Date> date(String v, String format) {
    ValueWrapper<Date> wrapper = new ValueWrapper<>();
    try {
      Date date = DateUtil.parse(v, format);
      wrapper.setValue(date);
    } catch (Exception e) {
      wrapper.setEx(e);
    }

    return wrapper;
  }

  private ValueWrapper<Date> timestamp(String v) {
    ValueWrapper<Date> wrapper = new ValueWrapper<>();
    try {
      long timestamp = Long.parseLong(v);
      Date date = new Date(timestamp);
      wrapper.setValue(date);
    } catch (Exception e) {
      wrapper.setEx(e);
    }

    return wrapper;
  }

  public static DateTimeDescribe compile(String dateTimeStr) {
    for (String regex : SUPPORT_REGEX_STR) {
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(dateTimeStr);
      if (matcher.matches() && matcher.groupCount() >= 3) {
        DateTimeDescribe describe = new DateTimeDescribe();
        StringBuilder sb = new StringBuilder();
        for (int k = 1; k <= matcher.groupCount(); k++) {
          Integer item = Integer.valueOf(matcher.group(k));
          if (k == 1 || k == 2) {
            sb.append(item).append('-');
            describe.setFormat(DatePattern.NORM_DATE_PATTERN);
          }
          if (k == 3) {
            sb.append(item);
            describe.setFormat(DatePattern.NORM_DATE_PATTERN);
          }
          if (k == 4) {
            sb.append(' ').append(item);
            describe.setFormat(DatePattern.NORM_DATETIME_MINUTE_PATTERN);
          }
          if (k == 5 || k == 6) {
            sb.append(':').append(item);
            describe.setFormat(DatePattern.NORM_DATETIME_PATTERN);
          }
        }
        describe.setValue(sb.toString());
        return describe;
      }
    }
    throw new RuntimeException(
        "Not support convert: " + dateTimeStr + ", regex: " + String.join(", ", SUPPORT_REGEX_STR));
  }
}
